Skip to content

fix(api): fix legacy model_type query compatibility for provider reads - #36427

Closed
QuantumGhost wants to merge 7 commits into
langgenius:mainfrom
QuantumGhost:codex/cus-1232-legacy-model-type-query-compat
Closed

QuantumGhost wants to merge 7 commits into
langgenius:mainfrom
QuantumGhost:codex/cus-1232-legacy-model-type-query-compat

Conversation

@QuantumGhost

@QuantumGhost QuantumGhost commented May 20, 2026 •

Copy link
Copy Markdown
Member

AI disclosure: This PR was primarily drafted with Codex using GPT-5.4. I have reviewed and edited the final diff, and I am responsible for the content.

Closes #36426 #36129 #36386

Summary

This fixes a regression in provider-side model credential reads for workspaces that still contain legacy model_type values in provider-related tables.

The important change in this revision is that the compatibility logic is now deterministic even when canonical and legacy rows coexist for the same logical scope:

  • single-row lookups now query canonical first and only fall back to legacy when canonical is missing
  • multi-row reads now fetch the raw persisted model_type string and prefer canonical rows during assembly; legacy rows are used only when the canonical counterpart does not exist for that scope

This keeps new writes on canonical enum values while making mixed datasets readable in a predictable way.

Historical context

There are two layers of ModelType history that matter here:

  1. Definition-level semantics

    • Before Model Runtime #1858, Dify still used provider-native strings such as text-generation, embeddings, and speech2text directly.
    • Model Runtime #1858 introduced the canonical internal ModelType values (llm, text-embedding, rerank, speech2text, moderation) plus compatibility helpers such as value_of() and to_origin_model_type().
    • tts models support #2033 later completed that canonical set by formally adding tts.
  2. Persistence-layer semantics

    • Even after canonical ModelType values existed in code, provider-related tables could still persist legacy/origin strings for compatibility.
    • refactor: use EnumText for model_type in provider models #34300 was the real persistence switch: new writes for provider-related model_type columns started using canonical enum values instead of legacy strings.
    • That created a mixed-data period where old rows could still contain values like text-generation, embeddings, and reranking, while new rows used llm, text-embedding, and rerank.

The short version is:

Cross references

  • refactor: use EnumText for model_type in provider models #34300 (1344c3b280) switched several provider tables to EnumText(ModelType) and removed the older to_origin_model_type() query normalization from controller/provider read paths.
  • fix: legacy model_type deserialization regression #34717 (e138523123) restored backward-compatible deserialization in EnumText.process_result_value(), so legacy persisted values could be loaded after a row was already selected.
  • chore(api): upgrade graphon to 0.4.0 #36124 upgraded the standalone graphon package to 0.4.0. That upgrade did not introduce a new ModelType semantic change, but it helped surface the remaining gap in Dify's query compatibility over mixed legacy/canonical rows.
  • The standalone graphon repository itself is not the source of this semantic transition. Its visible releases inherit the already-stable canonical/legacy mapping that Dify had established earlier.

Canonical vs legacy mapping

At the moment, the important compatibility pairs are:

  • llm <-> text-generation
  • text-embedding <-> embeddings
  • rerank <-> reranking

The other currently supported values (speech2text, moderation, tts) did not undergo the same string transition.

Root cause

ModelType.value_of("text-generation") still maps to ModelType.LLM, so once a row is fetched the in-memory value is fine.

The original failure happened earlier in SQL filtering:

  • request/query paths passed canonical values such as llm
  • SQLAlchemy bind parameters therefore emitted model_type = 'llm'
  • legacy rows that still stored text-generation were skipped before deserialization ever ran

After the first compatibility patch, another issue remained: if both canonical and legacy rows existed for the same logical scope, an OR-style compatibility filter could still produce ambiguous or unstable results. This PR removes that ambiguity by splitting the handling for single-row and multi-row queries.

Query inventory

Single-row queries

Scenario Location Category API
Read custom model record by provider + model + model_type ProviderConfiguration._get_custom_model_record() Single-row scalar_one_or_none()
Read a specific custom model credential by credential_id + model scope ProviderConfiguration._get_specific_custom_model_credential() Single-row scalar_one_or_none()
Read tenant default model by model_type ProviderManager.get_default_model() Single-row db.session.scalar()
Read existing tenant default model before update ProviderManager.update_default_model_record() Single-row db.session.scalar()
Read provider model setting by model + model_type ProviderConfiguration._get_provider_model_setting() Single-row first()
Read load-balancing config detail by config_id + model scope ModelLoadBalancingService.get_load_balancing_config() Single-row db.session.scalar(...limit(1))
Read model-level provider record for ops trace credential lookup ops_trace_manager._lookup_llm_credential_info() Single-row session.scalar()

Single-row queries inside write flows

Scenario Location Category API
Reuse hidden secret from existing custom model credential during validation ProviderConfiguration.validate_custom_model_credentials() Single-row scalar_one_or_none()
Read target custom model credential before update ProviderConfiguration.update_custom_model_credential() Single-row scalar_one_or_none()
Read target custom model credential before delete ProviderConfiguration.delete_custom_model_credential() Single-row scalar_one_or_none()
Read target custom model credential before adding it to model list ProviderConfiguration.add_model_credential_to_model() Single-row scalar_one_or_none()
Read target custom model credential before switching active credential ProviderConfiguration.switch_custom_model_credential() Single-row scalar_one_or_none()
Read custom model credential by credential_id while updating load-balancing configs ModelLoadBalancingService.update_load_balancing_configs() Single-row db.session.scalar(...limit(1))
Read existing load-balancing config by config_id during validation ModelLoadBalancingService.validate_load_balancing_credentials() Single-row db.session.scalar(...limit(1))

Multi-row queries

Scenario Location Category API
Read available custom model credentials for a provider + model + model_type scope ProviderManager.get_provider_model_available_credentials() Multi-row all()
Read load-balancing configs for a provider + model + model_type scope ModelLoadBalancingService.get_load_balancing_configs() Multi-row all()
Read current load-balancing configs before updating them ModelLoadBalancingService.update_load_balancing_configs() Multi-row all()
Bulk-load all valid provider models for workspace assembly ProviderManager._get_all_provider_models() Multi-row direct iteration over query results
Bulk-load all provider model settings for workspace assembly ProviderManager._get_all_provider_model_settings() Multi-row direct iteration over query results
Bulk-load all provider model credentials for workspace assembly ProviderManager._get_all_provider_model_credentials() Multi-row direct iteration over query results
Bulk-load all load-balancing configs for workspace assembly ProviderManager._get_all_provider_load_balancing_configs() Multi-row direct iteration over query results

Approach in this PR

1. Single-row queries: canonical-first fallback

For scalar_one_or_none(), scalar(), and first() style lookups, this PR no longer relies on a single canonical OR legacy filter.

Instead, the flow is explicit:

  1. query using the canonical enum value
  2. if no row is found, query using the legacy/origin string

This guarantees that when both canonical and legacy rows exist, the canonical row wins deterministically.

2. Multi-row queries: persisted-type-aware preference

For all() and bulk-iteration query paths, a pure fallback query is not sufficient because multiple rows may legitimately be returned.

For these paths, the query now includes an extra raw persisted type column using:

  • sa.type_coerce(model.model_type, sa.String())

The assembly layer then applies a small, isolated compatibility rule:

  • group rows by their logical scope
  • if canonical rows exist in that scope, use only the canonical rows
  • if canonical rows do not exist, use the legacy rows for that scope

This matters because once ORM deserialization runs, both llm and text-generation become ModelType.LLM in Python. The raw persisted string is therefore required to resolve precedence correctly.

3. Why the logic is isolated

The compatibility logic is kept in a dedicated helper module so it can be removed cleanly after the legacy rows are migrated away. The business modules only decide which query category they are in:

  • single-row lookup -> canonical-first fallback helper
  • multi-row assembly -> persisted-type-aware preference helper

User-visible failure

This showed up in CUS-1232 on OpenAI-compatible custom model credential flows:

  • opening custom model credentials could fail with Credential with id ... not found
  • saving or switching credentials could fail because the current credential/config row was not found
  • available credential lists and related load balancing/default-model lookups could also miss legacy rows in mixed datasets
  • when both canonical and legacy rows existed, some reads could also become ambiguous or nondeterministic

Scope of the fix

This PR applies the deterministic compatibility strategy to provider-side read paths, including:

  • custom model credential lookup
  • available custom model credential lists
  • provider model and default-model related reads
  • load-balancing config and credential reads
  • ops trace credential lookup
  • provider-manager bulk assembly helpers

The important boundary is intentional:

  • reads prefer canonical rows and only fall back to legacy when canonical is absent
  • writes still use canonical enum values
  • this PR does not perform a data migration or backfill

Why this shape

I kept the fix focused on read-path compatibility because it addresses the production failure immediately without mixing the hotfix with a broader data cleanup. A later migration can still normalize old rows once operational risk is lower.

Validation

  • make lint
  • make type-check
  • make test

@github-actions

github-actions Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Pyrefly Diff

base → PR
--- /tmp/pyrefly_base.txt	2026-05-21 06:31:45.691800849 +0000
+++ /tmp/pyrefly_pr.txt	2026-05-21 06:31:31.491656047 +0000
@@ -41,7 +41,7 @@
 ERROR No matching overload found for function `core.model_manager.ModelInstance.invoke_llm` called with arguments: (prompt_messages=list[SystemPromptMessage | UserPromptMessage], model_parameters=dict[str, float], stream=Literal[False]) [no-matching-overload]
    --> core/llm_generator/llm_generator.py:653:60
 ERROR Class member `OpsTraceProviderConfigMap.__getitem__` overrides parent class `UserDict` in an inconsistent manner [bad-override-param-name]
-   --> core/ops/ops_trace_manager.py:218:9
+   --> core/ops/ops_trace_manager.py:226:9
 ERROR `list[dict[str, str | dict[str, str]]] | list[Unknown]` is not assignable to TypedDict key `tool_calls` with type `list[dict[str, str]] | str` [bad-typed-dict-key]
   --> core/prompt/utils/prompt_message_util.py:83:44
 ERROR Argument `Unknown | None` is not assignable to parameter `result_object` with type `dict[str, Any]` in function `WaterCrawlProvider._structure_data` [bad-argument-type]
@@ -3991,21 +3991,23 @@
 ERROR Argument `SimpleNamespace` is not assignable to parameter `db_provider` with type `MCPToolProvider` in function `core.entities.mcp_provider.MCPProviderEntity.from_db_model` [bad-argument-type]
   --> tests/unit_tests/core/entities/test_entities_mcp_provider.py:59:46
 ERROR `None` is not subscriptable [unsupported-operation]
-   --> tests/unit_tests/core/entities/test_entities_provider_configuration.py:666:12
+   --> tests/unit_tests/core/entities/test_entities_provider_configuration.py:667:12
 ERROR Argument `SimpleNamespace` is not assignable to parameter `credential_record` with type `ProviderCredential | ProviderModelCredential` in function `core.entities.provider_configuration.ProviderConfiguration._update_load_balancing_configs_with_credential` [bad-argument-type]
-   --> tests/unit_tests/core/entities/test_entities_provider_configuration.py:894:31
+   --> tests/unit_tests/core/entities/test_entities_provider_configuration.py:895:31
 ERROR Argument `SimpleNamespace` is not assignable to parameter `credential_record` with type `ProviderCredential | ProviderModelCredential` in function `core.entities.provider_configuration.ProviderConfiguration._update_load_balancing_configs_with_credential` [bad-argument-type]
-   --> tests/unit_tests/core/entities/test_entities_provider_configuration.py:912:27
-ERROR `None` is not subscriptable [unsupported-operation]
-    --> tests/unit_tests/core/entities/test_entities_provider_configuration.py:1027:12
+   --> tests/unit_tests/core/entities/test_entities_provider_configuration.py:913:27
 ERROR `None` is not subscriptable [unsupported-operation]
     --> tests/unit_tests/core/entities/test_entities_provider_configuration.py:1028:12
 ERROR `None` is not subscriptable [unsupported-operation]
-    --> tests/unit_tests/core/entities/test_entities_provider_configuration.py:1044:12
+    --> tests/unit_tests/core/entities/test_entities_provider_configuration.py:1029:12
+ERROR `None` is not subscriptable [unsupported-operation]
+    --> tests/unit_tests/core/entities/test_entities_provider_configuration.py:1045:12
+ERROR `None` is not subscriptable [unsupported-operation]
+    --> tests/unit_tests/core/entities/test_entities_provider_configuration.py:1073:12
 ERROR `None` is not subscriptable [unsupported-operation]
-    --> tests/unit_tests/core/entities/test_entities_provider_configuration.py:1533:12
+    --> tests/unit_tests/core/entities/test_entities_provider_configuration.py:1565:12
 ERROR `None` is not subscriptable [unsupported-operation]
-    --> tests/unit_tests/core/entities/test_entities_provider_configuration.py:1725:12
+    --> tests/unit_tests/core/entities/test_entities_provider_configuration.py:1757:12
 ERROR Object of class `ModuleType` has no attribute `MockExtension` [missing-attribute]
   --> tests/unit_tests/core/extension/test_extensible.py:62:9
 ERROR Cannot index into `OrderedDict[str, ModuleExtension]` [bad-index]
@@ -6171,53 +6173,55 @@
 ERROR Argument `None` is not assignable to parameter `name` with type `str` in function `services.metadata_service.MetadataService.update_metadata_name` [bad-argument-type]
   --> tests/unit_tests/services/test_metadata_nullable_bug.py:51:85
 ERROR Object of class `ModelLoadBalancingService` has no attribute `provider_manager` [missing-attribute]
-  --> tests/unit_tests/services/test_model_load_balancing_service.py:76:5
-ERROR Object of class `ModelLoadBalancingService` has no attribute `model_assembly` [missing-attribute]
   --> tests/unit_tests/services/test_model_load_balancing_service.py:77:5
+ERROR Object of class `ModelLoadBalancingService` has no attribute `model_assembly` [missing-attribute]
+  --> tests/unit_tests/services/test_model_load_balancing_service.py:78:5
+ERROR Object of class `ModelLoadBalancingService` has no attribute `provider_manager` [missing-attribute]
+   --> tests/unit_tests/services/test_model_load_balancing_service.py:105:5
 ERROR Object of class `ModelLoadBalancingService` has no attribute `provider_manager` [missing-attribute]
-   --> tests/unit_tests/services/test_model_load_balancing_service.py:104:5
+   --> tests/unit_tests/services/test_model_load_balancing_service.py:125:5
 ERROR Object of class `ModelLoadBalancingService` has no attribute `provider_manager` [missing-attribute]
-   --> tests/unit_tests/services/test_model_load_balancing_service.py:124:5
+   --> tests/unit_tests/services/test_model_load_balancing_service.py:136:5
 ERROR Object of class `ModelLoadBalancingService` has no attribute `provider_manager` [missing-attribute]
-   --> tests/unit_tests/services/test_model_load_balancing_service.py:135:5
+   --> tests/unit_tests/services/test_model_load_balancing_service.py:154:5
 ERROR Object of class `ModelLoadBalancingService` has no attribute `provider_manager` [missing-attribute]
-   --> tests/unit_tests/services/test_model_load_balancing_service.py:153:5
+   --> tests/unit_tests/services/test_model_load_balancing_service.py:208:5
 ERROR Object of class `ModelLoadBalancingService` has no attribute `provider_manager` [missing-attribute]
-   --> tests/unit_tests/services/test_model_load_balancing_service.py:204:5
+   --> tests/unit_tests/services/test_model_load_balancing_service.py:266:5
 ERROR Object of class `ModelLoadBalancingService` has no attribute `provider_manager` [missing-attribute]
-   --> tests/unit_tests/services/test_model_load_balancing_service.py:258:5
+   --> tests/unit_tests/services/test_model_load_balancing_service.py:328:5
 ERROR Object of class `ModelLoadBalancingService` has no attribute `provider_manager` [missing-attribute]
-   --> tests/unit_tests/services/test_model_load_balancing_service.py:271:5
+   --> tests/unit_tests/services/test_model_load_balancing_service.py:341:5
 ERROR Object of class `ModelLoadBalancingService` has no attribute `provider_manager` [missing-attribute]
-   --> tests/unit_tests/services/test_model_load_balancing_service.py:290:5
+   --> tests/unit_tests/services/test_model_load_balancing_service.py:360:5
 ERROR Object of class `ModelLoadBalancingService` has no attribute `provider_manager` [missing-attribute]
-   --> tests/unit_tests/services/test_model_load_balancing_service.py:330:5
+   --> tests/unit_tests/services/test_model_load_balancing_service.py:400:5
 ERROR Object of class `ModelLoadBalancingService` has no attribute `provider_manager` [missing-attribute]
-   --> tests/unit_tests/services/test_model_load_balancing_service.py:349:5
+   --> tests/unit_tests/services/test_model_load_balancing_service.py:419:5
 ERROR Object of class `ModelLoadBalancingService` has no attribute `provider_manager` [missing-attribute]
-   --> tests/unit_tests/services/test_model_load_balancing_service.py:369:5
+   --> tests/unit_tests/services/test_model_load_balancing_service.py:439:5
 ERROR Object of class `ModelLoadBalancingService` has no attribute `provider_manager` [missing-attribute]
-   --> tests/unit_tests/services/test_model_load_balancing_service.py:390:5
+   --> tests/unit_tests/services/test_model_load_balancing_service.py:460:5
 ERROR Object of class `ModelLoadBalancingService` has no attribute `provider_manager` [missing-attribute]
-   --> tests/unit_tests/services/test_model_load_balancing_service.py:412:5
+   --> tests/unit_tests/services/test_model_load_balancing_service.py:482:5
 ERROR Object of class `ModelLoadBalancingService` has no attribute `provider_manager` [missing-attribute]
-   --> tests/unit_tests/services/test_model_load_balancing_service.py:443:5
+   --> tests/unit_tests/services/test_model_load_balancing_service.py:513:5
 ERROR Object of class `ModelLoadBalancingService` has no attribute `provider_manager` [missing-attribute]
-   --> tests/unit_tests/services/test_model_load_balancing_service.py:465:5
+   --> tests/unit_tests/services/test_model_load_balancing_service.py:541:5
 ERROR Object of class `ModelLoadBalancingService` has no attribute `provider_manager` [missing-attribute]
-   --> tests/unit_tests/services/test_model_load_balancing_service.py:498:5
+   --> tests/unit_tests/services/test_model_load_balancing_service.py:584:5
 ERROR Object of class `ModelLoadBalancingService` has no attribute `provider_manager` [missing-attribute]
-   --> tests/unit_tests/services/test_model_load_balancing_service.py:547:5
+   --> tests/unit_tests/services/test_model_load_balancing_service.py:644:5
 ERROR Object of class `ModelLoadBalancingService` has no attribute `provider_manager` [missing-attribute]
-   --> tests/unit_tests/services/test_model_load_balancing_service.py:578:5
+   --> tests/unit_tests/services/test_model_load_balancing_service.py:675:5
 ERROR Object of class `ModelLoadBalancingService` has no attribute `provider_manager` [missing-attribute]
-   --> tests/unit_tests/services/test_model_load_balancing_service.py:606:5
+   --> tests/unit_tests/services/test_model_load_balancing_service.py:703:5
 ERROR Object of class `ModelLoadBalancingService` has no attribute `provider_manager` [missing-attribute]
-   --> tests/unit_tests/services/test_model_load_balancing_service.py:625:5
+   --> tests/unit_tests/services/test_model_load_balancing_service.py:722:5
 ERROR Object of class `ModelLoadBalancingService` has no attribute `provider_manager` [missing-attribute]
-   --> tests/unit_tests/services/test_model_load_balancing_service.py:647:5
+   --> tests/unit_tests/services/test_model_load_balancing_service.py:744:5
 ERROR Object of class `ModelLoadBalancingService` has no attribute `model_assembly` [missing-attribute]
-   --> tests/unit_tests/services/test_model_load_balancing_service.py:673:37
+   --> tests/unit_tests/services/test_model_load_balancing_service.py:770:37
 ERROR `(tenant_id: str) -> service_with_fake_configurations._FakeProviderManager` is not assignable to attribute `_get_provider_manager` with type `(tenant_id: str) -> ProviderManager` [bad-assignment]
   --> tests/unit_tests/services/test_model_provider_service_sanitization.py:74:33
 ERROR Argument `dict[str, Any]` is not assignable to parameter `utm_info` with type `UtmInfo` in function `services.operation_service.OperationService.record_utm` [bad-argument-type]

@github-actions

github-actions Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Pyrefly Type Coverage

Metric Base PR Delta
Type coverage 0.00% 44.56% +44.56%
Strict coverage 0.00% 44.08% +44.08%
Typed symbols 0 22,902 +22,902
Untyped symbols 0 28,801 +28,801
Modules 0 2615 +2,615

@autofix-ci

autofix-ci Bot commented May 20, 2026

Copy link
Copy Markdown
Contributor

Hi! I'm autofix logoautofix.ci, a bot that automatically fixes trivial issues such as code formatting in pull requests.

I would like to apply some automated changes to this pull request, but it looks like I don't have the necessary permissions to do so. To get this pull request into a mergeable state, please do one of the following two things:

  1. Allow edits by maintainers for your pull request, and then re-trigger CI (for example by pushing a new commit).
  2. Manually fix the issues identified for your pull request (see the GitHub Actions output for details on what I would like to change).

@QuantumGhost QuantumGhost changed the title [codex] fix legacy model_type query compatibility for provider reads fix(api): fix legacy model_type query compatibility for provider reads May 20, 2026
@QuantumGhost

QuantumGhost commented May 21, 2026 •

Copy link
Copy Markdown
Member Author

After a private discussion with @hjlarry, we concluded that a data migration is likely a simpler and more complete solution to this problem.

The main considerations are as follows:

  1. For single-row queries (for example, first() or scalar_one_or_none()), changing the predicate from model_type = :canonical_model_type to model_type IN (:canonical_model_type, :legacy_model_type) looks straightforward at first glance. In practice, however, the result is not deterministic when canonical and legacy rows coexist for the same logical scope. Unless every such query also defines an explicit precedence, the selected row is effectively undefined.

  2. For queries that return multiple rows, the approach above is not sufficient. We would need to fetch both canonical and legacy rows, preserve the persisted model_type, and then apply canonical-first deduplication in Python. Some of these read paths already perform additional grouping or assembly in Python, which makes the logic harder to implement correctly and reason about.

  3. The original goal was to provide a hotfix. However, once we account for the query categories above, the required compatibility logic becomes fairly broad and touches multiple read paths. That makes the change scope larger than what we would normally want for a hotfix.

  4. Even if implemented correctly, this would still be only a temporary workaround. As long as legacy values remain in the database, both existing code and future code will need to carry this additional complexity. Migrating legacy rows to canonical values is therefore a more thorough way to solve the problem and reduce long-term maintenance burden.

Considering the points above, we believe a data migration is the more robust approach.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Legacy model_type values break custom model credential management

1 participant